<template>
  <div class="commission-rate">
    <e-container class="search-area">
      <SearchInput searchText="Branch">
        <a-select
          v-model:value="branch"
          show-search
          option-filter-prop="label"
          option-label-prop="label"
          :get-popup-container="triggerNode => triggerNode.parentNode"
          style="width: 15vw"
        >
          <a-select-option v-for="item in branchList" :key="item.id" :label="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </SearchInput>
    </e-container>
    <a-spin :spinning="loading">
      <div v-if="list.length > 0" class="commissions">
        <commission-card
          v-for="data in list"
          :key="data.employee"
          :data="data"
          :readonly="!isPrimaryCSO"
          @edit="handleEdit(data)"
        />
      </div>
      <div v-else>
        <e-empty centered />
      </div>
    </a-spin>
    <a-modal
      v-model:visible="showEditModel"
      width="888px"
      title="Set Subject"
      wrap-class-name="primary-modal unlimited-height"
      ok-text="Save"
      :mask-closable="false"
      :destroy-on-close="true"
      @cancel="showEditModel = false"
      @ok="handleSave"
    >
      <commission-edit ref="editHandle" :raw-data="editData" />
    </a-modal>
  </div>
</template>

<script setup>
import { inject, nextTick, onMounted, ref, watch, computed } from 'vue'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import SearchInput from '../../components/SearchInput.vue'
import CommissionCard from './components/commission/card.vue'
import CommissionEdit from './components/commission/edit.vue'
import sp from '@/api/salesPlan.js'
import CommissionRate from '@/api/commissionRate.js'
import EEmpty from '@/components/EEmpty.vue'
import { OPERATION_SUCCESSFUL } from '@/constants/message.js'
const { message } = inject('Feedback')
// BU
const branch = ref()
const branchList = ref([])

const loading = ref(false)
const list = ref([])
const editData = ref({})
const editHandle = ref(null)

// 角色，只有集团销售总监有编辑权限
const store = useStore()
const isPrimaryCSO = computed(() => store.getters['user/isPrimaryCSO'])
/**
 * 获取当前人管理Branch信息
 */
const getBranch = () => {
  sp.getBranch().then(res => {
    if (res.code === 2000) {
      branchList.value = res.data
      branch.value = branchList.value[0].id
    }
  })
}
/**
 * 初始化
 */
onMounted(() => {
  getBranch()
})
const showEditModel = ref(false)
const handleEdit = data => {
  editData.value = data
  showEditModel.value = true
  nextTick(() => {
    editHandle.value.init()
  })
}
const handleSave = () => {
  editHandle.value
    .validate()
    .then(({ option, employee, yearPercents, amountPercents, yearQuotaPercent, monthPercent }) => {
      let updateFunction
      if (option === 1) {
        updateFunction = CommissionRate.setSubject.bind(this, employee, yearPercents, amountPercents)
      } else {
        updateFunction = CommissionRate.setSubjectOverseas.bind(
          this,
          employee,
          yearPercents,
          yearQuotaPercent,
          monthPercent
        )
      }
      updateFunction(employee, yearPercents, amountPercents).then(res => {
        message.success(OPERATION_SUCCESSFUL)
        showEditModel.value = false
        loadData(branch.value)
      })
    })
    .catch(e => {
      console.log(e.toString())
    })
}
watch(branch, value => {
  loading.value = true
  loadData(value)
})
const loadData = value => {
  CommissionRate.list(value)
    .then(({ data }) => {
      list.value = data
    })
    .finally(() => {
      loading.value = false
    })
}
</script>

<style lang="less" scoped>
.commissions {
  display: flex;
  flex-wrap: wrap;
  .e-container {
    width: calc(100% / 3 - 16px);
    margin-top: 24px;
    &:nth-child(3n - 1) {
      margin-left: 24px;
      margin-right: 24px;
    }
  }
}
</style>

<route lang="yaml">
name: Commission Rate
path: '/sales-settings/commission-rate'
meta:
  title: Commission Rate
  sort: 3
  roles: isPrimaryCSO, isBranchCSO
</route>
